using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;

namespace PackTracker.Business
{ 
	[Serializable()] 
	public class Endereco : Csla.BusinessBase<Endereco>
	{
		#region Business Properties and Methods

		//declare members
		private int _id = 0;
		private string _logradouro = string.Empty;
		private string _bairro = string.Empty;
		private string _cidade = string.Empty;
		private string _estado = string.Empty;
		private string _pais = string.Empty;
		private int _cep = 0;

		[System.ComponentModel.DataObjectField(true, true)]
		public int Id
		{
			get
			{
				CanReadProperty("Id", true);
				return _id;
			}
		}

		public string Logradouro
		{
			get
			{
				CanReadProperty("Logradouro", true);
				return _logradouro;
			}
			set
			{
				CanWriteProperty("Logradouro", true);
				if (value == null) value = string.Empty;
				if (!_logradouro.Equals(value))
				{
					_logradouro = value;
					PropertyHasChanged("Logradouro");
				}
			}
		}

		public string Bairro
		{
			get
			{
				CanReadProperty("Bairro", true);
				return _bairro;
			}
			set
			{
				CanWriteProperty("Bairro", true);
				if (value == null) value = string.Empty;
				if (!_bairro.Equals(value))
				{
					_bairro = value;
					PropertyHasChanged("Bairro");
				}
			}
		}

		public string Cidade
		{
			get
			{
				CanReadProperty("Cidade", true);
				return _cidade;
			}
			set
			{
				CanWriteProperty("Cidade", true);
				if (value == null) value = string.Empty;
				if (!_cidade.Equals(value))
				{
					_cidade = value;
					PropertyHasChanged("Cidade");
				}
			}
		}

		public string Estado
		{
			get
			{
				CanReadProperty("Estado", true);
				return _estado;
			}
			set
			{
				CanWriteProperty("Estado", true);
				if (value == null) value = string.Empty;
				if (!_estado.Equals(value))
				{
					_estado = value;
					PropertyHasChanged("Estado");
				}
			}
		}

		public string Pais
		{
			get
			{
				CanReadProperty("Pais", true);
				return _pais;
			}
			set
			{
				CanWriteProperty("Pais", true);
				if (value == null) value = string.Empty;
				if (!_pais.Equals(value))
				{
					_pais = value;
					PropertyHasChanged("Pais");
				}
			}
		}

		public int Cep
		{
			get
			{
				CanReadProperty("Cep", true);
				return _cep;
			}
			set
			{
				CanWriteProperty("Cep", true);
				if (!_cep.Equals(value))
				{
					_cep = value;
					PropertyHasChanged("Cep");
				}
			}
		}
 
		protected override object GetIdValue()
		{
			return _id;
		}

		#endregion //Business Properties and Methods

		#region Validation Rules
		private void AddCustomRules()
		{
			//add custom/non-generated rules here...
		}

		private void AddCommonRules()
		{
			//
			// Logradouro
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Logradouro");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Logradouro", 200));
			//
			// Bairro
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Bairro");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Bairro", 50));
			//
			// Cidade
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Cidade");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Cidade", 50));
			//
			// Estado
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Estado");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Estado", 2));
			//
			// Pais
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Pais");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Pais", 50));
		}

		protected override void AddBusinessRules()
		{
			AddCommonRules();
			AddCustomRules();
		}
		#endregion //Validation Rules

		#region Authorization Rules
		protected override void AddAuthorizationRules()
		{
			//TODO: Define authorization rules in Endereco
			//AuthorizationRules.AllowRead("Id", "EnderecoReadGroup");
			//AuthorizationRules.AllowRead("Logradouro", "EnderecoReadGroup");
			//AuthorizationRules.AllowRead("Bairro", "EnderecoReadGroup");
			//AuthorizationRules.AllowRead("Cidade", "EnderecoReadGroup");
			//AuthorizationRules.AllowRead("Estado", "EnderecoReadGroup");
			//AuthorizationRules.AllowRead("Pais", "EnderecoReadGroup");
			//AuthorizationRules.AllowRead("Cep", "EnderecoReadGroup");

			//AuthorizationRules.AllowWrite("Logradouro", "EnderecoWriteGroup");
			//AuthorizationRules.AllowWrite("Bairro", "EnderecoWriteGroup");
			//AuthorizationRules.AllowWrite("Cidade", "EnderecoWriteGroup");
			//AuthorizationRules.AllowWrite("Estado", "EnderecoWriteGroup");
			//AuthorizationRules.AllowWrite("Pais", "EnderecoWriteGroup");
			//AuthorizationRules.AllowWrite("Cep", "EnderecoWriteGroup");
		}


		public static bool CanGetObject()
		{
			//TODO: Define CanGetObject permission in Endereco
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("EnderecoViewGroup"))
			//	return true;
			//return false;
		}

		public static bool CanAddObject()
		{
			//TODO: Define CanAddObject permission in Endereco
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("EnderecoAddGroup"))
			//	return true;
			//return false;
		}

		public static bool CanEditObject()
		{
			//TODO: Define CanEditObject permission in Endereco
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("EnderecoEditGroup"))
			//	return true;
			//return false;
		}

		public static bool CanDeleteObject()
		{
			//TODO: Define CanDeleteObject permission in Endereco
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("EnderecoDeleteGroup"))
			//	return true;
			//return false;
		}
		#endregion //Authorization Rules

		#region Factory Methods
		private Endereco()
		{ /* require use of factory method */ }

		public static Endereco NewEndereco()
		{
			if (!CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Endereco");
			return DataPortal.Create<Endereco>();
		}

		public static Endereco GetEndereco(int id)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a Endereco");
			return DataPortal.Fetch<Endereco>(new Criteria(id));
		}

		public static void DeleteEndereco(int id)
		{
			if (!CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Endereco");
			DataPortal.Delete(new Criteria(id));
		}

		public override Endereco Save()
		{
			if (IsDeleted && !CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Endereco");
			else if (IsNew && !CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Endereco");
			else if (!CanEditObject())
				throw new System.Security.SecurityException("User not authorized to update a Endereco");

			return base.Save();
		}

		#endregion //Factory Methods

		#region Child Factory Methods
		internal static Endereco NewEnderecoChild()
		{
			Endereco child = new Endereco();
			child.ValidationRules.CheckRules();
			child.MarkAsChild();
			return child;
		}

		internal static Endereco GetEndereco(SafeDataReader dr)
		{
			Endereco child =  new Endereco();
			child.MarkAsChild();
			child.Fetch(dr);
			return child;
		}
		#endregion //Child Factory Methods

		#region Data Access

		#region Criteria

		[Serializable()]
		private class Criteria
		{
			public int Id;

			public Criteria(int id)
			{
				this.Id = id;
			}
		}

		#endregion //Criteria

		#region Data Access - Create
		[RunLocal]
		protected override void DataPortal_Create()
		{
			ValidationRules.CheckRules();
		}

		#endregion //Data Access - Create

		#region Data Access - Fetch
		private void DataPortal_Fetch(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteFetch(cn, criteria);
			}//using
		}

		private void ExecuteFetch(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_GetEndereco";
				cm.Parameters.AddWithValue("@id", criteria.Id);

				using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
				{
					dr.Read();
					FetchObject(dr);
					ValidationRules.CheckRules();

					//load child object(s)
					FetchChildren(dr);
				}
			}//using
		}

		#endregion //Data Access - Fetch

		#region Data Access - Insert
		protected override void DataPortal_Insert()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteInsert(cn);

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Insert

		#region Data Access - Update
		protected override void DataPortal_Update()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				if (base.IsDirty)
				{
					ExecuteUpdate(cn);
				}

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Update

		#region Data Access - Delete
		protected override void DataPortal_DeleteSelf()
		{
			DataPortal_Delete(new Criteria(_id));
		}

		private void DataPortal_Delete(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteDelete(cn, criteria);

			}//using

		}

		private void ExecuteDelete(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_DeleteEndereco";

				cm.Parameters.AddWithValue("@id", criteria.Id);

				cm.ExecuteNonQuery();
			}//using
		}
		#endregion //Data Access - Delete

		#region Data Access - Fetch
		private void Fetch(SafeDataReader dr)
		{
			FetchObject(dr);
			MarkOld();
			ValidationRules.CheckRules();

			//load child object(s)
			if(!this.IsChild)
				FetchChildren(dr);
		}

		private void FetchObject(SafeDataReader dr)
		{
			_id = dr.GetInt32("id");
			_logradouro = dr.GetString("Logradouro");
			_bairro = dr.GetString("Bairro");
			_cidade = dr.GetString("Cidade");
			_estado = dr.GetString("Estado");
			_pais = dr.GetString("Pais");
			_cep = dr.GetInt32("CEP");
		}

		private void FetchChildren(SafeDataReader dr)
		{
		}
		#endregion //Data Access - Fetch

		#region Data Access - Insert
		internal void Insert(SqlConnection cn)
		{
			if (!IsDirty) return;

			ExecuteInsert(cn);
			MarkOld();

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteInsert(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_AddEndereco";

				AddInsertParameters(cm);

				cm.ExecuteNonQuery();

				_id = (int)cm.Parameters["@id"].Value;
			}//using
		}

		private void AddInsertParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@Logradouro", _logradouro);
			cm.Parameters.AddWithValue("@Bairro", _bairro);
			cm.Parameters.AddWithValue("@Cidade", _cidade);
			cm.Parameters.AddWithValue("@Estado", _estado);
			cm.Parameters.AddWithValue("@Pais", _pais);
			if (_cep != 0)
				cm.Parameters.AddWithValue("@CEP", _cep);
			else
				cm.Parameters.AddWithValue("@CEP", DBNull.Value);
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters["@id"].Direction = ParameterDirection.Output;
		}
		#endregion //Data Access - Insert

		#region Data Access - Update
		internal void Update(SqlConnection cn)
		{
			if (!IsDirty) return;

			if (base.IsDirty)
			{
				ExecuteUpdate(cn);
				MarkOld();
			}

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteUpdate(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_UpdateEndereco";

				AddUpdateParameters(cm);

				cm.ExecuteNonQuery();

			}//using
		}

		private void AddUpdateParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters.AddWithValue("@Logradouro", _logradouro);
			cm.Parameters.AddWithValue("@Bairro", _bairro);
			cm.Parameters.AddWithValue("@Cidade", _cidade);
			cm.Parameters.AddWithValue("@Estado", _estado);
			cm.Parameters.AddWithValue("@Pais", _pais);
			if (_cep != 0)
				cm.Parameters.AddWithValue("@CEP", _cep);
			else
				cm.Parameters.AddWithValue("@CEP", DBNull.Value);
		}

		private void UpdateChildren(SqlConnection cn)
		{
		}
		#endregion //Data Access - Update

		#region Data Access - Delete
		internal void DeleteSelf(SqlConnection cn)
		{
			if (!IsDirty) return;
			if (IsNew) return;

			ExecuteDelete(cn, new Criteria(_id));
			MarkNew();
		}
		#endregion //Data Access - Delete
		#endregion //Data Access
	}
}
